#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
from django.shortcuts import render, redirect, reverse, HttpResponse
from django.views import View

from app01.models import *


def publish_list(request):
    publishs = Publish.objects.all()
    return render(request, "bookmanage/publish/publish_list.html",
                  {"publish_list": publishs})


def publish_delete(request, id):
    get_publish_id = Publish.objects.filter(pk=id)
    if get_publish_id.first():
        get_publish_id.delete()
    return redirect(reverse("publish_list"))


class Publishadd(View):
    def get(self, request):
        return render(request, "bookmanage/publish/publish_add.html")

    def post(self, request):
        name = request.POST.get("name")
        address = request.POST.get("address")
        # 忽略错误，直接返回
        try:
            Publish.objects.create(name=name, address=address)
        except:
            pass
        return redirect(reverse("publish_list"))


class Publishchange(View):
    def get(self, request, id):
        get_aid = Publish.objects.filter(pk=id)
        if get_aid:
            return render(request, "bookmanage/publish/publish_change.html",
                          {"auther": get_aid.first()})
        return redirect(reverse("auther_list"))

    def post(self, request, id):
        get_aid = Publish.objects.filter(pk=id)
        if get_aid:
            name = request.POST.get("name")
            address = request.POST.get("address")

            get_aid = get_aid.first()
            get_aid.name = name
            get_aid.address = address
            get_aid.save()

            return redirect(reverse("publish_list"))
